package com.smartcruise.main.selfFragment.setting;

import android.widget.Button;
import android.widget.TextView;

import com.smartcruise.R;
import com.smartcruise.base.BaseTitleFragment;
import com.smartcruise.base.TitleBuilder;
import com.smartcruise.data.ReportData;
import com.smartcruise.data.cruiseData.CruiseData;
import com.smartcruise.data.cruiseData.NodeTaskListBean;
import com.smartcruise.util.FileUtils;
import com.smartcruise.util.Key;
import com.smartcruise.util.ListUtils;
import com.smartcruise.util.TempleUser;
import com.smartcruise.util.network.callBack.SimpleCallBack;
import com.smartcruise.util.network.customerObserver.SimpleProgressObserverImp;
import com.smartcruise.util.network.netUtils.Result;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import io.realm.Realm;
import io.realm.RealmResults;

/**
 * Created by FengChaoQun
 * on 2018/3/8 0008
 * 清除缓存界面
 */

public class CleanDataFragment extends BaseTitleFragment {

    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.imageCache)
    TextView imageCache;
    @BindView(R.id.videoCache)
    TextView videoCache;
    @BindView(R.id.audioCache)
    TextView audioCache;

    private List<String> unusedImage = new ArrayList<>();
    private List<String> unusedVideo = new ArrayList<>();
    private List<String> unusedAudio = new ArrayList<>();
    private Disposable disposable;
    private boolean isCountEnd;//标记缓存数据是否计算完成

    @Override
    protected void init() {
        setCloseActivity();
        Observable.create(new ObservableOnSubscribe<Result>() {
            @Override
            public void subscribe(ObservableEmitter<Result> observableEmitter) throws Exception {

                /*
                * 首先记录下在使用的资源
                * */
                List<String> usedImage = new ArrayList<>();
                List<String> usedVideo = new ArrayList<>();
                List<String> usedAudio = new ArrayList<>();

                try (Realm realm = Realm.getDefaultInstance()) {

                    RealmResults<CruiseData> allCruise = realm.where(CruiseData.class)
                            .equalTo(Key.inspectorId, TempleUser.getInstance().getAccount())
                            .findAll();
                    for (CruiseData cruiseData : allCruise) {
                        if (ListUtils.isHaveContent(cruiseData.getNodeTaskList())) {
                            for (NodeTaskListBean nodeTaskListBean : cruiseData.getNodeTaskList()) {
                                if (ListUtils.isHaveContent(nodeTaskListBean.getOriginalImage())) {
                                    usedImage.addAll(nodeTaskListBean.getOriginalImage());
                                }
                                if (ListUtils.isHaveContent(nodeTaskListBean.getOriginalVideos())) {
                                    usedVideo.addAll(nodeTaskListBean.getOriginalVideos());
                                }
                                if (ListUtils.isHaveContent(nodeTaskListBean.getOriginalAudios())) {
                                    usedAudio.addAll(nodeTaskListBean.getOriginalAudios());
                                }
                            }
                        }
                    }

                    RealmResults<ReportData> allReport = realm.where(ReportData.class)
                            .equalTo(Key.inspectorId, TempleUser.getInstance().getAccount())
                            .findAll();
                    for (ReportData reportData : allReport) {
                        if (ListUtils.isHaveContent(reportData.getOriginalImage())) {
                            usedImage.addAll(reportData.getOriginalImage());
                        }
                        if (ListUtils.isHaveContent(reportData.getOriginalVideos())) {
                            usedVideo.addAll(reportData.getOriginalVideos());
                        }
                        if (ListUtils.isHaveContent(reportData.getOriginalAudios())) {
                            usedAudio.addAll(reportData.getOriginalAudios());
                        }
                    }
                }

                /*
                * 计算不再需要的图片的大小
                * 1.glide缓存图片
                * 2.缩略图
                * 3.临时图片
                * 4.未在数据库中出现过的图片
                * */
                File glideCache = new File(FileUtils.getGlideCache());
                File imageThumbnail = new File(FileUtils.getImageThumPath());
                File imageTemple = new File(FileUtils.getImageTemplePath());
                File savedImage = new File(FileUtils.getImagePath());
                long imageSize = FileUtils.getFolderSize(glideCache) + FileUtils.getFolderSize(imageThumbnail) + FileUtils.getFolderSize(imageTemple);

                //找出所有的未使用的图片
                File[] images = savedImage.listFiles();
                if (images != null) {
                    for (File file : images) {
                        if (!usedImage.contains(file.getAbsolutePath())) {
                            unusedImage.add(file.getAbsolutePath());
                            imageSize += file.length();
                        }
                    }
                }

                String imageFormatSize = FileUtils.getFormatSize(imageSize);
                Result imageResult = new Result();
                imageResult.setCode(1);
                imageResult.setMessage(imageFormatSize);
                observableEmitter.onNext(imageResult);

                /*
                * 计算不再需要的视频的大小
                * */

                //找出所有未使用的视频
                File videoFile = new File(FileUtils.getVideoPath());
                File[] videos = videoFile.listFiles();
                long videoSize = 0;
                if (videos != null) {
                    for (File file : videos) {
                        if (!usedVideo.contains(file.getAbsolutePath())) {
                            unusedVideo.add(file.getAbsolutePath());
                            videoSize += file.length();
                        }
                    }
                }

                String videoFormatSize = FileUtils.getFormatSize(videoSize);
                Result videoResult = new Result();
                videoResult.setCode(2);
                videoResult.setMessage(videoFormatSize);
                observableEmitter.onNext(videoResult);

                /*
                * 计算不在需要的音频的大小
                * */
                //找出所有未使用的音频
                File audioFile = new File(FileUtils.getAudioPath());
                File[] audios = audioFile.listFiles();
                long audioSize = 0;
                if (audios != null) {
                    for (File audio : audios) {
                        if (!usedAudio.contains(audio.getAbsolutePath())) {
                            unusedAudio.add(audio.getAbsolutePath());
                            audioSize += audio.length();
                        }
                    }
                }
                String audioFormatSize = FileUtils.getFormatSize(audioSize);
                Result audioResult = new Result();
                audioResult.setCode(3);
                audioResult.setMessage(audioFormatSize);
                observableEmitter.onNext(audioResult);

                observableEmitter.onComplete();

            }
        }).subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Result>() {
                    @Override
                    public void onSubscribe(Disposable disposable) {
                        CleanDataFragment.this.disposable = disposable;
                    }

                    @Override
                    public void onNext(Result result) {
                        switch (result.getCode()) {
                            case 1:
                                imageCache.setText("图片缓存:" + result.getMessage());
                                break;
                            case 2:
                                videoCache.setText("视频缓存:" + result.getMessage());
                                break;
                            case 3:
                                audioCache.setText("音频缓存:" + result.getMessage());
                                break;

                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        showToast(throwable.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        isCountEnd = true;
                    }
                });
    }

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_container_clean_data;
    }

    @Override
    protected TitleBuilder getTitleBuilder() {
        return TitleBuilder.create(true, "清理缓存");
    }

    @OnClick(R.id.button)
    public void onViewClicked() {
        if (!isCountEnd) {
            showToast("请等待计算完成");
            return;
        }

        Observable.create(new ObservableOnSubscribe<Result>() {
            @Override
            public void subscribe(ObservableEmitter<Result> observableEmitter) throws Exception {
                FileUtils.deleteFolderFile(FileUtils.getImageTemplePath(), false);
                FileUtils.deleteFolderFile(FileUtils.getImageThumPath(), false);
                FileUtils.deleteFolderFile(FileUtils.getGlideCache(), false);
                for (String s : unusedImage) {
                    File file = new File(s);
                    file.delete();
                }
                for (String s : unusedVideo) {
                    File file = new File(s);
                    file.delete();
                }
                for (String s : unusedAudio) {
                    File file = new File(s);
                    file.delete();
                }
                Result result = new Result();
                result.setCode(2000);
                observableEmitter.onNext(result);
                observableEmitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SimpleProgressObserverImp(this, new SimpleCallBack(this) {
                    @Override
                    public void onSuccess(Result result) {
                        showToast("清除缓存成功");
                        getActivity().finish();
                    }
                }));
    }

    @Override
    public void onLeftArrowClicked() {
        getActivity().finish();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (disposable != null) {
            disposable.dispose();
        }
    }
}
